import React, { useEffect, useState } from 'react';
// 引入个人设置
import {
  NavBar,
  TextArea,
  Button,
  Modal,
  Form,
  ActionSheet,
  Toast,
} from 'antd-mobile';
// 引入 icon 图标
import { RightOutline } from 'antd-mobile-icons';

// 引入less文件
import './person.less';
import axios from 'axios';

import type { Action } from 'antd-mobile/es/components/action-sheet';
import { history } from 'umi';

export default function person() {
  // 保存表单数据
  const [form] = Form.useForm();
  // 获取 token
  const [token, setToken] = useState(sessionStorage.getItem('token') || '');
  // 从本地存储中获取个人信息
  const [personalInfo, setPersonalInfo] = useState(
    JSON.parse(sessionStorage.getItem('userdata') || '{}') || '',
  );
  // 保存个人信息
  const [data, setData] = useState({
    face: '',
    username: '',
    nickname: '',
    gender: '',
  });
  // 控制用户名显示隐藏
  const [visible, setVisible] = useState(false);
  // 控制昵称显示隐藏
  const [nickvisible, setNickVisible] = useState(false);
  // 控制性别显示隐藏
  const [sex, setSex] = useState(false);
  const actions: Action[] = [
    { text: '男', key: '男' },
    { text: '女', key: '女' },
  ];
  // 控制头像显示隐藏
  const [tou, setTou] = useState(false);
  const touactions: Action[] = [
    { text: '使用微信头像', key: 'wechart' },
    { text: '使用QQ空间头像', key: 'QQ' },
    { text: '使用新浪微博头像', key: 'Sina' },
    { text: '拍照上传', key: 'phone' },
    { text: '从相册中选取', key: 'album' },
  ];

  useEffect(() => {
    getPerson();
  }, []);

  // 点击按钮返回
  const back = () => {
    history.push('/install');
  };

  // 点击修改个人信息
  const tijiao = async () => {
    let username = form.getFieldsValue().username;
    let nickname = form.getFieldsValue().nickname;
    let gender = form.getFieldsValue().gender;
    console.log(gender);

    // 请求修改接口
    let {
      data: { code },
    } = await axios.post('api/mine/updPerson', {
      id: personalInfo._id,
      username: username,
      nickname: nickname,
    });
    if (code === 200) {
      getPerson();
    }
    setNickVisible(false);
    setVisible(false);
  };

  // 获取个人信息
  const getPerson = async () => {
    if (token) {
      let {
        data: { code, msg, data },
      } = await axios.get(`/api/mine/getPerson?id=${personalInfo._id}`);
      if (code == 200) {
        let dataForm = data[0];
        setData({ ...dataForm });
      }
    }
  };

  // 用来显示修改表单，修改数据 用户名和昵称
  const handler = (
    vis: boolean,
    name: string,
    set: (t: boolean) => void,
    itemname: string,
    max: number,
  ) => {
    return (
      <>
        {/* 修改昵称 */}
        <Modal
          visible={vis}
          header={
            <p>
              <span className="modal-title">修改{name}</span>
              <span onClick={() => set(false)}>
                <svg
                  className="close-icon"
                  viewBox="0 0 1024 1024"
                  version="1.1"
                  xmlns="http://www.w3.org/2000/svg"
                  p-id="2624"
                  width="12"
                  height="12"
                >
                  <path
                    d="M512 456.310154L94.247385 38.557538a39.542154 39.542154 0 0 0-55.689847 0 39.266462 39.266462 0 0 0 0 55.689847L456.310154 512 38.557538 929.752615a39.542154 39.542154 0 0 0 0 55.689847 39.266462 39.266462 0 0 0 55.689847 0L512 567.689846l417.752615 417.752616c15.163077 15.163077 40.290462 15.36 55.689847 0a39.266462 39.266462 0 0 0 0-55.689847L567.689846 512 985.442462 94.247385a39.542154 39.542154 0 0 0 0-55.689847 39.266462 39.266462 0 0 0-55.689847 0L512 456.310154z"
                    fill="#707070"
                    p-id="2625"
                  ></path>
                </svg>
              </span>
            </p>
          }
          content={
            <>
              <Form
                form={form}
                footer={
                  <Button
                    className="save"
                    onClick={tijiao}
                    block
                    type="submit"
                    color="primary"
                    size="large"
                  >
                    保存
                  </Button>
                }
              >
                <Form.Item
                  label={`${name}:`}
                  name={`${itemname}`}
                  rules={[{ max: max - 1, message: '最多支持15个字' }]}
                >
                  <TextArea
                    placeholder="请输入"
                    maxLength={max}
                    showCount
                    defaultValue={
                      itemname === 'nickname'
                        ? data.nickname
                        : itemname === 'username'
                        ? data.username
                        : ''
                    }
                  />
                </Form.Item>
              </Form>
            </>
          }
        />
      </>
    );
  };

  // 修改性别
  const actionHandler = async (action: any) => {
    let {
      data: { code, msg, data },
    } = await axios.post('api/mine/updSex', {
      id: personalInfo._id,
      gender: action.text,
    });
    if (code == 200) {
      Toast.show({
        icon: 'success',
        content: '修改性别成功',
      });
      getPerson();
    }
  };

  // 头像上传
  const touactionHandler = (action: any) => {
    if (action.key === 'album') {
      history.push('/album');
    }
  };

  return (
    <div className="person">
      {/* 个人信息顶部 */}
      <div className="person-top">
        <NavBar onBack={back}>个人信息</NavBar>
      </div>

      <div className="person-all">
        <div className="person-box">
          <div
            className="person-left"
            style={{ lineHeight: '45px' }}
            onClick={() => setTou(true)}
          >
            头像
          </div>
          <div className="person-right">
            <img
              onClick={() => setTou(true)}
              src={data.face}
              alt=""
              style={{ width: '43px', height: '43px', marginRight: '3px' }}
            />
            <RightOutline
              style={{ verticalAlign: '.5em' }}
              fontSize={'18px'}
              color="#cccccc"
            />
          </div>
        </div>

        <div className="person-box">
          <div className="person-left">用户名</div>
          <div className="person-right">
            <span
              onClick={() => {
                setVisible(true);
              }}
            >
              {data.username}
            </span>
            <RightOutline
              style={{ verticalAlign: '-0.2em' }}
              fontSize={'18px'}
              color="#cccccc"
            />
          </div>
        </div>

        <div className="person-box">
          <div className="person-left">昵称</div>
          <div className="person-right">
            <span
              onClick={() => {
                setNickVisible(true);
              }}
            >
              {data.nickname}
            </span>
            <RightOutline
              style={{ verticalAlign: '-0.2em' }}
              fontSize={'18px'}
              color="#cccccc"
            />
          </div>
        </div>

        <div className="person-box">
          <div className="person-left">性别</div>
          <div className="person-right">
            <span
              onClick={() => {
                setSex(true);
              }}
            >
              {data.gender}
            </span>
            <RightOutline
              style={{ verticalAlign: '-0.2em' }}
              fontSize={'18px'}
              color="#cccccc"
            />
          </div>
        </div>

        <div className="person-box">
          <div className="person-left">出生日期</div>
          <div className="person-right">
            <span>{'124M'}</span>
            <RightOutline
              style={{ verticalAlign: '-0.2em' }}
              fontSize={'18px'}
              color="#cccccc"
            />
          </div>
        </div>
      </div>
      {/* 头像 */}
      <ActionSheet
        extra="使用第三方头像绑定第三方账号"
        cancelText="取消"
        visible={tou}
        actions={touactions}
        closeOnAction
        closeOnMaskClick={false}
        onClose={() => setTou(false)}
        onAction={(action) => touactionHandler(action)}
      />

      {/* 用户名 */}
      {visible
        ? handler(visible, '用户名', setVisible, 'username', 10)
        : handler(visible, '用户名', setVisible, 'username', 10)}
      {/* 昵称 */}
      {nickvisible
        ? handler(nickvisible, '昵称', setNickVisible, 'nickname', 15)
        : handler(nickvisible, '昵称', setNickVisible, 'nickname', 15)}
      {/* 性别 */}
      <ActionSheet
        extra="请选择性别"
        cancelText="取消"
        visible={sex}
        actions={actions}
        closeOnAction
        closeOnMaskClick={false}
        onClose={() => setSex(false)}
        onAction={(action) => actionHandler(action)}
      />
      {/* 出生日期 */}
    </div>
  );
}
